package com.wangsong.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangsong.model.User;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.TreeMap;

@Component
public class MyMessageConverter extends AbstractHttpMessageConverter<Object> {

    public MyMessageConverter() {
        // 构造方法中指明consumes（req）和produces（resp）的类型，指明这个类型才会使用这个converter
        super(MediaType.APPLICATION_JSON);


    }

    @Override
    protected boolean supports(Class aClass) {
        return User.class.equals(aClass);
    }

    @Override
    protected Object readInternal(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String temp = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
        User jsonObject = JSON.parseObject(temp, User.class);
        //解密
        jsonObject.setAge(jsonObject.getAge() + 1);
        return jsonObject;
    }

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(object);
        User jsonObject = JSON.parseObject(json, User.class);
        //加密
        jsonObject.setAge(jsonObject.getAge() - 1);
        String result = JSON.toJSONString(jsonObject);
        outputMessage.getBody().write(result.getBytes());
    }
}
